package com.lmx.repoDomain.repository;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.CustomerService;
import com.lmx.persistence.service.DeviceService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Device;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(Device.class)
@Component
public class DeviceRepository extends BaseRepository<Device>{
	
	@Autowired
	private CustomerService customerService; 
	
	@Autowired
	private DeviceService deviceService; 

    @PostConstruct
    public void init() {
        dslJpaService.setEntityClass(Device.class); 
    }

    
	@Override
	@JsonApiSave
	public Device save(Device model) {
		if (model.getId() == null) {
			//验证该设备类型中此编号是否已被绑定
			Device temp = customerService.getDeviceBySeq(model);
			if (temp == null) {
				//添加如果为摄像头
				if (model.getType() != null && model.getDeviceType() != null
						&& "video".equals(model.getType().getCodeInfo())
						&& "deviceTypeVideo".equals(model.getDeviceType().getTypecode())) {
					model = deviceService.createCameraDevice(model);
				} else {
					model = super.save(model);
				}
			} else {
				model.setErrcode(4);// seq重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
			}
		} else {
			if (model.getDelStatus() == 1) {// 删除
				//判断已绑定提示不能删除
				int deleteFlag = deviceService.checkDeviceRelations(model);
				if (deleteFlag > 0) {
					model.setErrcode(8);// no delete
					throw new BusinessException(null, CommonConstants.ERROR_CODE.NO_DELETE.label(), null);
				}
				dslJpaService.update(model);
			} else {
				if (model.getOperateFlag() != null && ((CommonConstants.DEVICE_OPERATE_CODE.BIND.label().equals(model.getOperateFlag())
						|| (CommonConstants.DEVICE_OPERATE_CODE.REMOVE_BIND.label().equals(model.getOperateFlag()))))) {// 进行解绑或者绑定操作
					deviceService.operateDeviceByFlag(model,null);
				} else {// 修改device信息
					Device temp = customerService.getDeviceBySeqFilterId(model);
					if (temp == null) {
						dslJpaService.update(model);
					} else {
						model.setErrcode(4);// 名字重复
						throw new BusinessException(null, CommonConstants.ERROR_CODE.NAME_ERROR.label(), null);
					}
				}
				// 复位操作
				if (model.getOperateFlag() != null && ("reset".equals(model.getOperateFlag()))) {
					deviceService.resetDevice(model);
				}
				// 开通直播
				if (model.getOperateFlag() != null && ("startLive".equals(model.getOperateFlag()))) {
					model = deviceService.startLiveService(model);
					if (model.getErrcode() == 0) {
						model.setErrcode(14);// 开通服务有误
						throw new BusinessException(null, CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
					}
				}
			}
		}
		return model;
	}
   

	@Override
	@JsonApiFindAll
	public Iterable<Device> findAll(final QueryParams requestParams) {
		Map<String, String> keyMap = CommonUtil.getKeyMapByFilter(requestParams);
		Iterable<Device> deviceList = new ArrayList<>();
		List dataList = new ArrayList<>();
		String queryData = "";
		String queryType = "";
		String typeCode = "";  // 硬件方案  code
		Short deviceStatus=-1;//  1  可用  0  不可用
		String deviceType="";//   设备类型的 code
		if (keyMap.get("type.codeInfo") != null) {//查询条件
			typeCode = keyMap.get("type.codeInfo");
		}
		if (keyMap.get("queryData") != null) {//查询条件
			queryData = keyMap.get("queryData");
		}
		if (keyMap.get("queryType") != null) {//查询类型
			queryType = keyMap.get("queryType");
		}
		if (keyMap.get("deviceStatus") != null&&keyMap.get("deviceStatus").matches("\\d+")) {//查询条件
			deviceStatus =Short.valueOf(keyMap.get("deviceStatus"));
		}
		if (keyMap.get("deviceType.typecode") != null) {
			deviceType = keyMap.get("deviceType.typecode");
		}
		if ("queryAll".equals(queryType)) {
			// 搜索device from Customer Employee Room bed
			dataList = deviceService.getDeviceFromAll(queryData,deviceStatus,deviceType,typeCode);
			commonService.setPageInfo(dataList, requestParams);
			deviceList = dataList;
		} else if (queryType != null && queryType.contains("startLive")) {
			String queryIds = "0";
			String type = "0";
			//老人id
			if(queryType.contains("@cid")){
				queryIds=queryType.replace("startLive@cid", "");
				type="customer";
			}
			//床位id
			if(queryType.contains("@bid")){
				queryIds=queryType.replace("startLive@bid", "");
				type="bed";
			}
			//房间id
			if(queryType.contains("@rid")){
				queryIds=queryType.replace("startLive@rid", "");
				type="room";
			}
			//设备id
			if(queryType.contains("@did")){
				queryIds=queryType.replace("startLive@did", "");
				type="device";
			}
			return customerService.startLiveVideo(queryIds,type);
		} else if (queryType != null && queryType.contains("endLive")) {
			String queryIds = "0";
			String type = "0";
			//老人id
			if(queryType.contains("@cid")){
				queryIds=queryType.replace("endLive@cid", "");
				type="customer";
			}
			//床位id
			if(queryType.contains("@bid")){
				queryIds=queryType.replace("endLive@bid", "");
				type="bed";
			}
			//房间id
			if(queryType.contains("@rid")){
				queryIds=queryType.replace("endLive@rid", "");
				type="room";
			}
			//设备id
			if(queryType.contains("@did")){
				queryIds=queryType.replace("endLive@did", "");
				type="device";
			}
			return customerService.stopLiveVideo(queryIds,type);
		} else {
			dslJpaService.setEntityClass(Device.class);
			return super.findAll(requestParams);
		}
		return deviceList;
	}
	
}
